package com.process.shareMemory;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class SharedMemoryProducer {
    public static void main(String[] args) {
        try {
            // 创建文件和文件通道
            RandomAccessFile file = new RandomAccessFile("D:\\shared_memory.dat", "rw");
            FileChannel channel = file.getChannel();

            // 创建共享内存缓冲区
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);

            // 生产者进程向共享内存写入数据
            for (int i = 0; i < 100; i++) {
                String data = "Data " + i;
                buffer.put(data.getBytes());
                System.out.println("Producer: " + data);
                Thread.sleep(1000);
            }

            // 关闭文件通道和文件
            channel.close();
            file.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
